define(
	['require', 'angular', 'angularAMD', 'angularMaterial','angular-route', 'ylc-common'],
	function (require, angular, angularAMD) {
		var app = angular.module('cys', ['ui.router', 'ylc.common','ngMaterial','ngAria','ngMessages'])
		app.constant('pathPrefix', '')
		ngHtmlDirective.$inject = ['$parse', '$compile'];

		function ngHtmlDirective($parse, $compile) {
			return {
				restrict: 'A',
				priority: 999,
				link: function (scope, element, attr) {
					var old;
					function getValue() {
						try {
							return scope.$eval(attr.ngHtml)
						} catch (e) {
							return scope[attr.ngHtml];
						}
					}
					scope.$watch(getValue, function ngBindHtmlWatchAction(value) {
						if (old == value) {
							return;
						}
						old = value;
						element.html(value);
						$compile(element.contents())(scope);
					});
				}
			}
		}
		app.directive('ngHtml', ngHtmlDirective)

        app.directive('myOnFocus', function() {
            return {
                scope: true,
                restrict: 'A',
                link: function(scope, elem, attr, ctrl) {
                    elem.bind('focus', function() {
                        if (scope[attr.myOnFocus]) {
                            elem.triggerHandler('click');
                        }
                    });
                    elem.bind('blur', function() {
                        scope[attr.myOnFocus] = true;
                    });
                }
            };
        });

		function LoginCtrl($injector, $http, $scope, $rootScope) {
			var self = this
			self.switchLogin = function () {
				if (!$rootScope.$user) {
					return;
				}
				if ($rootScope.$user.type == -1) {
					if ($rootScope.$loginUrl) {
						location.href = ($rootScope.$loginUrl)
					} else
						self.openDialog()
				} else {
					location.href = require.toUrl('root/login/logout')
				}
			}
			self.openDialog = function () {
				require(['root/components/common/modal/modal'], function () {
					var modalService = $injector.get('modalService')
					self.modalService = modalService
					self.currentDialog = modalService.show({
						title: '登陆',
						contentUrl: 'components/login.html',
						ctrl: self,
						validateRules: {
							messages: {
								username: "请输入用户名",
								password: "请输入密码"
							}
						}
					})
				})
			}
			self.login = function (username, password) {
				self.error = ''
				if (!username) {
					return;
				}
				if (!password) {
					return;
				}
				self.message = '正在登陆中...'
				self.onlogin = true
				$http.post('login/login', {
					username: username,
					password: password
				}).success(function (r) {
					if (r || r === 0) {
						self.modalService.succ('登陆成功', 1000)
						setTimeout(function () {
							self.currentDialog.close()
							location.reload()
						}, 1000)
					} else {
						self.error = '用户名或密码错误'
					}
				})['finally'](function () {
					self.message = ''
					self.onlogin = false
				})
			}
			
			//校验是否登录
			self.checkLogin = function (event,type_) {
				var modalService = $injector.get('modalService')
				if (!$rootScope.$user) {
					return;
				}
				var roleType = $rootScope.$user.type;
				if (roleType == -1) {
					modalService.error('请先登录', 1500)
					return;
				}else{
					if($rootScope.$user.teacher==0){//学生
						if(type_ == 1){
							modalService.error('暂无权访问', 1500)
							return;
							//location.href = 'index2.html#/manager';//团员信息采集
						}else if(type_ == 2){
							//判断是否考勤员表中人员
							$http.post(':root/kq/getKyqCount').success(function (r) {
								if(r == 0){
									modalService.error('系统建设中', 1500)
									return;
								}
								$("div.con").removeClass("hide");
							})
						}else if(type_ == 3){//磐石计划
							modalService.error('系统建设中', 1500)
							return;
							//location.href = '';
						}else if(type_ == 4){//社会实践
							modalService.error('系统建设中', 1500)
							return;
							//location.href = 'organization.html';
						}
					}else{
						if(roleType == 0){//0教师
							if(type_ == 1){
								modalService.error('暂无权访问', 1500)
								return;
							}
						}else if(roleType == 1){//1院系管理员
							if(type_ == 1){
								location.href = '#/organization';//团组织管理地址
							}
						}else if(roleType == 2 || roleType == 3){//2学校管理员
							if(type_ == 1){
								location.href = '#/organization';//管理地址
								/*app.component('organization', {
									templateUrl: ':root/organization.html',
									controller: function () {}
								})*/
							}
						}else if(roleType == 4){//支部管理员
							if(type_ == 1){
								location.href = '#/manager';//团员信息采集
							}
						}
						
						if(type_ == 2){
							//判断是否考勤员表中人员
							$http.post(':root/kq/getKyqCount').success(function (r) {
								if(r == 0){
									modalService.error('系统建设中', 1500)
									return;
								}
								$("div.con").removeClass("hide");
							})
						}
						
						if(type_ == 3){//磐石计划
							modalService.error('暂无权访问', 1500)
							return;
							//location.href = '';
						}else if(type_ == 4){//社会实践
							modalService.error('暂无权访问', 1500)
							return;
							//location.href = 'organization.html';
						}
					}
					
					//location.href = $(event.target).parent().attr('data-url');
				}
			}
			
			self.checkLogin1 = function (event,type_) {
				var modalService = $injector.get('modalService')
				if(type_ == 2){//青马工程
					modalService.error('系统建设中', 1500)
					return;
				}else{
					//打卡中心
                    location.href = 'dakacenter.html';
				}
			}
		}
		app.controller('LoginCtrl', LoginCtrl)

		configHttp.$inject = ['$httpProvider']

		function configHttp($httpProvider) {
			$httpProvider.defaults.withCredentials = true;
			$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
			var param = function (obj) {
				var query = '', name, value, fullSubName, subName, subValue, innerObj, i;
				for (name in obj) {
					value = obj[name];
					if (value instanceof Array) {
						for (i = 0; i < value.length; ++i) {
							subValue = value[i];
							if (angular.isObject(subValue)) {
								fullSubName = name + '[' + i + ']';
							} else {
								fullSubName = name; // + '[' + i + ']';
							}
							innerObj = {};
							innerObj[fullSubName] = subValue;
							query += param(innerObj) + '&';
						}
					} else if (angular.isDate(value)) {
						query += encodeURIComponent(name) + '=' + encodeURIComponent(value.getTime()) + '&';
					} else if (value instanceof Object) {
						for (subName in value) {
							subValue = value[subName];
							fullSubName = name + '.' + subName;
							innerObj = {};
							innerObj[fullSubName] = subValue;
							query += param(innerObj) + '&';
						}
					} else if (value !== undefined && value !== null)
						query += encodeURIComponent(name) + '=' + encodeURIComponent(value) + '&';
				}
				return query.length ? query.substr(0, query.length - 1) : query;
			}
			$httpProvider.defaults.transformRequest = [function (data) {
				return angular.isObject(data) && String(data) !== '[object File]' ? param(data) : data;
			}]
			$httpProvider.defaults.transformResponse = [function defaultHttpResponseTransform(data, headers) {
				if (angular.isString(data)) {
					var tempData = data.replace(/^\)]\}',?\n/, "").trim();
					if (tempData) {
						var contentType = headers("Content-Type");
						if (contentType && contentType.indexOf('application/json') === 0) {
							try {
								data = angular.fromJson(tempData);
							} catch (error) {
							}
						}
					}
				}
				return data;
			}]
			rootPathInterceptor.$inject = ['$q', '$injector'];

			function rootPathInterceptor($q, $injector) {
				var request = function (config) {
					var u = config.url;
					var s = u.charAt(0);
					if (s == ':') {
						config.url = require.toUrl(u.substring(1))
					}
					return config;
				}
				var requestError = function (rejection) {
					require(
						['root/components/common/modal/modal'],
						function () {
							var modalService = $injector.get('modalService')
							if (rejection.status == 401) {
								modalService
									.error('请您<a href="javascript:;" ng-controller="LoginCtrl as ctrl" ng-click="ctrl.switchLogin()">登录</a>后再进行操作')
							} else if (rejection.status == 405) {
								modalService.error('权限不足', 1500)
							} else {
								var message = '请求失败'
								var time = 1200
								if (rejection.data && rejection.data.length < 20) {
									message = message + ',' + rejection.data
									time += 1800
								}
								modalService.error(message, time)
							}
						})
					return $q.reject(rejection);
				}
				return {
					'request': request,
					'responseError': requestError
				};
			}
			$httpProvider.interceptors.push(rootPathInterceptor);
		}
		app.config(configHttp);
		app.config(function ($controllerProvider) {
			$controllerProvider.allowGlobals && $controllerProvider.allowGlobals();
		})
		function autofocus() {
			return {
				restrict: 'A',
				link: function (scope, element, attr) {
					setTimeout(function () {
						element.focus()
					}, 500)

				}
			}
		}
		app.directive('autofocus', autofocus)
		CtrlUtil.$inject = ['$http', '$injector']
		function CtrlUtil($http, $injector) {
			var CtrlUtil = this;
			this.getQueryParams = function (ctrl) {
				var param = {}
				angular.forEach(ctrl, function (v, k) {
					k = k + ''
					var i = k.lastIndexOf('QueryParam')
					if ((i > 0 && i == (k.length - 10)) && v != '') {
						param[k.substring(0, i)] = angular.isFunction(v) ? v() : v
					}
				})
				param.pageNumber = ctrl.pageNumber
				param.pageSize = ctrl.pageSize
				return param;
			}
			this.resetQueryParams = function (ctrl) {
				angular.forEach(ctrl, function (v, k) {
					k = k + ''
					var i = k.lastIndexOf('QueryParam')
					if ((i > 0 && i == (k.length - 10))) {
						ctrl[k] = ''
					}
				})
			}
			this.loadDepartment = function (target) {
				return $http.post(':root/department/queryByStatusAndType', {
					status: 1,
					type: 1
				}).success(function (r) {
					target.departments = r
					target.departmentMap = {}
					angular.forEach(r, function (v) {
						target.departmentMap[v.id] = v
					})
					return r;
				})
			}
			this.loadMajor = function (target, department) {
				return $http.post(':root/major/getMajors', {
					department: department
				}).success(function (r) {
					target.majors = r
					target.majorMap = {}
					angular.forEach(r, function (v) {
						target.majorMap[v.id] = v
					})
					return r;
				})
			}

			this.checkAll = function (ctrl, check) {
				angular.forEach(ctrl.entities.content, function (v, k) {
                    if (!v.$disableCheck) {
						v.$checked = check
                    }
				})
			}
			this.getChecked = function (ctrl) {
				var r = [];
				angular.forEach(ctrl.entities.content, function (v, k) {
					v.$checked && r.push(v)
				})
				return r;
			}
			this.build = function (ctrl, query, paramObj) {
				paramObj = paramObj || ctrl
				ctrl.pageNumber = 0
				ctrl.query = function () {
					ctrl.entities && (ctrl.entities.content = {})
					var p = CtrlUtil.getQueryParams(paramObj)
					var p1 = CtrlUtil.getQueryParams(ctrl)
					angular.extend(p, p1)
					$http.post(query, p).success(function (r) {
						var q, b = ctrl.onQuerySuccess && (q = ctrl.onQuerySuccess(r))
						if (q && q.then) {
							q.then(function () {
								ctrl.entities = r;
							})
						} else {
							ctrl.entities = r;
						}
					})
				};
				ctrl.reset = function () {
					CtrlUtil.resetQueryParams(ctrl)
				};
				ctrl.checkAll = function (b) {
					CtrlUtil.checkAll(ctrl, b)
				}
				ctrl.getChecked = function(){
					CtrlUtil.getChecked(ctrl);
				}
			}
			this.toImageUrl = function (tpId, course) {
				var UploadService = $injector.get('UploadService')
				var imageUrl = tpId ? (UploadService.getServerUrl() + '/preview/getImage?hash=' + tpId.split('/')[0] + '&size='
					+ tpId.split('/')[1] + (course ? '&w=280&h=170' : '')) : 'asset/img/defaultCourse.jpg'
				return imageUrl;

			}
			this.toDownloadUrl = function (file, name) {
				var split = file.split('/')
				return require.toUrl('root/file/downloadPopByHash') + '?hash=' + split[0] + '&size=' + split[1] + '&name=' + name;
			}
			this.getIds = function (content) {
				var ids = []
				angular.forEach(content, function (v) {
					ids.push(v.id)
				})
				return ids;
			}
			this.addProperty = function (content, ext, field, idproperty, idtarget) {
				var map = {}
				angular.forEach(ext, function (v) {
					if (angular.isArray(v)) {
						map[v[0]] = v[1]
					} else if (angular.isObject(v)) {
						var id = v;
						if (idproperty) {
							var ar = idproperty.split('.')
							var t;
							while (t = ar.shift()) {
								id = id[t]
							}
						} else {
							id = id.id
						}
						map[id] = v
					}
				})
				angular.forEach(content, function (v) {
					var id = v;
					if (idtarget) {
						var ar = idtarget.split('.')
						var t;
						while (t = ar.shift()) {
							id = id[t]
						}
					} else {
						id = id.id
					}
					v[field] = map[id]
				})
			}
			return this;
		}
		/*app.component('courseList', {
			bindings: {
				filter: '<',
				myCourse: '<',
			},
			require: {
			},
			templateUrl: ':root/components/common/courseDisplay.html',
			controller: function () {
			}
		})*/
		app.component('homepage', {
			templateUrl: ':root/homepage.html',
			controller: function () {}
		})
		app.factory('CtrlUtil', CtrlUtil)
		app.filter('toBool', function () {
			return function (arg) {
				var r = !!arg
				return r ? '是' : '否'
			}
		});
		app.filter('toSex',function(){
			return function (arg){
				var r = '';
				if(r == 1){
					r = '女';
				}else if(r == 0){
					r = '男';
				}
				return r;
			}
		})
		app.filter('auditString', function () {
			return function (arg) {
				var r = '未知'
				switch (arg) {
					case -1:
						r = '请求驳回'
						break;
					case 0:
						r = '草稿'
						break;
					case 1:
						r = '待院系审核'
						break;
					case 2:
						r = '待学校审核'
						break;
					case 3:
						r = '审核通过'
						break;
				}
				return r;
			}
		})
		app.filter('br', function () {
			return function (arg) {
				return arg ? arg.replace(/\r\n/g, '<br>').replace(/\n/g, '<br>').replace(/\r/g, '<br>') : arg;
			}
		})
		app.filter('unexpired', function ($rootScope) {
			return function (arg) {
				return $rootScope.$server && (arg > $rootScope.$server.time);
			}
		})
		app.filter('nullText', function () {
			return function (arg) {
				if (arg == undefined) {
					return '-'
				}
				return arg;
			}
		})
		app.filter('courseType', function () {
			return function (arg) {
				arg = arg + ''
				var r = ''
				switch (arg) {
					case '1':
						r = '必修课'
						break;
					case '2':
						r = '选修课'
						break;
					case '3':
						r = '体验课'
						break;
					default:
						r = '未知'
				}
				return r;
			}
		})
        app.filter('cc', function () {
            return function (arg) {
                arg = arg + ''
                var r = ''
                switch (arg) {
                    case '1':
                        r = '必修课'
                        break;
                    case '2':
                        r = '选修课'
                        break;
                    case '3':
                        r = '体验课'
                        break;
                    default:
                        r = '未知'
                }
                return r;
            }
        })
		app.directive('input', function () {
			return {
				restrict: 'E',
				priority: 10,
				require: '?ngModel',
				link: function (scope, $el, attrs, ngModel) {
					if (attrs.type === 'number' && ngModel) {
						ngModel.$parsers.push(function (value) {
							return value.toString();
						});

						ngModel.$formatters.push(function (value) {
							return parseFloat(value, 10);
						});
					}
				}
			}
		})
		function resetHash() {
			var t = location.hash
			location.hash = ''
			setTimeout(function () {
				location.hash = t
				if (!location.hash) {
					location.hash = '/'
				}
			})

		}

		function routerCallBack() {
			angularAMD.config(function ($urlRouterProvider, $stateProvider) {
				$urlRouterProvider.otherwise('/home');
				resetHash();
			})
		}
		Init.$inject = ['$http', '$rootScope', '$state', '$locale', 'CtrlUtil']
		function Init($http, $rootScope, $state, $locale, CtrlUtil) {
			define('$rootScope', [], function () {
				return $rootScope;
			})
			$rootScope.$state = $state
			$rootScope.toUrl = require.toUrl
			$rootScope.toImageUrl = CtrlUtil.toImageUrl
			CtrlUtil.loadDepartment($rootScope)
			$rootScope.toDownloadUrl = CtrlUtil.toDownloadUrl
			$rootScope['export'] = function (ctrl, url, param) {
				url = require.toUrl(url)
				var ctrlParams = CtrlUtil.getQueryParams(ctrl)
				param && angular.extend(ctrlParams, param)
				var form = $('<form action="' + url + '" method="POST" target="_blank">')
				angular.forEach(ctrlParams, function (v, k) {
					if (v != '' && v != undefined)
						form.append($('<input name="' + k + '" value="' + v + '">'))
				})
				$(window.document.body).append(form)
				form.submit()
				form.remove()
			}

			var offset = 0
			$rootScope.getCurrentDate = function () {
				return new Date(new Date().getTime() - offset);
			}
			$http.post(':root/common/time').then(function (response) {
				offset = (new Date().getTime() - response.data)
				$rootScope.currentDate = $rootScope.getCurrentDate();
			})
			$http.post(':root/login/getCurrent').success(function (r) {
				$rootScope.$currentUserInfo = r;
				$rootScope.$user = r[0]
				if (r[2] === -1) {
					require(['ngload!root/asset/js/router-public'], routerCallBack)
				} else if (r[2] === 0) {
					require(['ngload!root/asset/js/router-public', 'ngload!root/asset/js/router-stu'], routerCallBack)
				} else {
					require(['ngload!root/asset/js/router-manager', 'ngload!root/asset/js/router-public'], routerCallBack)
				}
				$rootScope.switchRole = function (role) {
					location.href = (require.toUrl("root/login/switchRole") + '?toRole=' + role.type);
					return true;
				}
				require(['bootstrap'])
			})
			$http.post(':root/course/time').success(function (r) {
				$rootScope.$server = $rootScope.$server || {}
				$rootScope.$server.time = r
			})
			$http.post(':root/login/getLoginUrl').success(function (r) {
				$rootScope.$loginUrl = r
			})
			
			//查询当前用户人员角色
			/*if($rootScope.$user.teacher == 1){
				$http.post(':root/login/getUserRoleUrl',{
					uid: $rootScope.$user.uid
				}).success(function (v) {
					var roles=[]
					angular.forEach(R, function (v) {
						roles.push({
							type : v.type,
							name : v.name
						})
					})
					console.log('roles='+roles)
					$rootScope.$userRoles = roles
				})
			}*/
		}
		app.run(Init)
		ConfigLocal.$inject = ["$provide"]
		function ConfigLocal($provide) {
			var PLURAL_CATEGORY = {
				ZERO: "zero",
				ONE: "one",
				TWO: "two",
				FEW: "few",
				MANY: "many",
				OTHER: "other"
			};
			$provide.value("$locale",
				{
					"DATETIME_FORMATS": {
						"AMPMS": ["\u4e0a\u5348", "\u4e0b\u5348"],
						"DAY": ["\u661f\u671f\u65e5", "\u661f\u671f\u4e00", "\u661f\u671f\u4e8c", "\u661f\u671f\u4e09",
							"\u661f\u671f\u56db", "\u661f\u671f\u4e94", "\u661f\u671f\u516d"],
						"MONTH": ["\u4e00\u6708", "\u4e8c\u6708", "\u4e09\u6708", "\u56db\u6708", "\u4e94\u6708", "\u516d\u6708",
							"\u4e03\u6708", "\u516b\u6708", "\u4e5d\u6708", "\u5341\u6708", "\u5341\u4e00\u6708",
							"\u5341\u4e8c\u6708"],
						"SHORTDAY": ["\u5468\u65e5", "\u5468\u4e00", "\u5468\u4e8c", "\u5468\u4e09", "\u5468\u56db",
							"\u5468\u4e94", "\u5468\u516d"],
						"SHORTMONTH": ["1\u6708", "2\u6708", "3\u6708", "4\u6708", "5\u6708", "6\u6708", "7\u6708", "8\u6708",
							"9\u6708", "10\u6708", "11\u6708", "12\u6708"],
						"fullDate": "y\u5e74M\u6708d\u65e5EEEE",
						"longDate": "y\u5e74M\u6708d\u65e5",
						"medium": "y\u5e74M\u6708d\u65e5 ah:mm:ss",
						"mediumDate": "y\u5e74M\u6708d\u65e5",
						"mediumTime": "ah:mm:ss",
						"short": "yy/M/d ah:mm",
						"shortDate": "yy/M/d",
						"shortTime": "ah:mm"
					},
					"NUMBER_FORMATS": {
						"CURRENCY_SYM": "\u00a5",
						"DECIMAL_SEP": ".",
						"GROUP_SEP": ",",
						"PATTERNS": [{
							"gSize": 3,
							"lgSize": 3,
							"maxFrac": 3,
							"minFrac": 0,
							"minInt": 1,
							"negPre": "-",
							"negSuf": "",
							"posPre": "",
							"posSuf": ""
						}, {
							"gSize": 3,
							"lgSize": 3,
							"maxFrac": 2,
							"minFrac": 2,
							"minInt": 1,
							"negPre": "\u00a4\u00a0-",
							"negSuf": "",
							"posPre": "\u00a4\u00a0",
							"posSuf": ""
						}]
					},
					"id": "zh-cn",
				});
		}
		app.config(ConfigLocal);
		return angularAMD.bootstrap(app);
	})
